import json
import random
import logging
logger = logging.getLogger('django')

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from meiduo001.libs.captcha.captcha import captcha

from meiduo001.libs.yuntongxun.ccp_sms import CCP


class ImageCodeView(View):
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()

        # 连接redis数据库,创建连接对象
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, 300, text)
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    def get(self, request, mobile):
        # 1.获取参数
        redis_conn = get_redis_connection('verify_code')
        send_conf = redis_conn.get('send_conf%s' % mobile)
        if send_conf:
            return JsonResponse({'code':400,'errmsg':'短信发送过于频繁'})
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 2.检验参数
        if not all([image_code_client, uuid]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必要参数'})

        # 3建立连接对象
        redis_conn = get_redis_connection('verify_code')
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码过期'})

        # 删除图形验证码,避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)
        if image_code_client.lower() != image_code_server.decode().lower():
            return JsonResponse({'code': 400,
                                 'errmsg': '图形验证码输入错误'})

        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)
        logger.info(sms_code)
        # redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        # redis_conn.setex('send_flag_%s' % mobile, 60, 1)
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()

        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        return JsonResponse({'code': 0,
                             'errmsg': 'ok'})
